/**
 * 
 */
package hichecker.ui.components;

import java.awt.IllegalComponentStateException;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

/**
 *
 */
public class CustomPopUp extends JPopupMenu {

	private JComponent invoker;

	/**
	 * Creates a popup
	 */
	public CustomPopUp() {
	}

	/**
	 * Sets the component the popup belongs to
	 * 
	 * @param invoker
	 */
	public void setInvoker(JComponent invoker) {
		this.invoker = invoker;

		// Set the location relative to the invoker's position
		Point location;
		try {
			location = invoker.getLocationOnScreen();
		} catch (IllegalComponentStateException e) {
			location = invoker.getLocation();
		}
		location.y = location.y + 42;
		setLocation(location);

		// Add motion listener to the invoker's parent and to the popup itself
		MouseMotionListener listener = new MouseMotionAdapter() {
			@Override
			public void mouseMoved(MouseEvent e) {
				hideIt();
			}
		};
		invoker.getParent().addMouseMotionListener(listener);
		addMouseMotionListener(listener);

		// Add keylistener to invoker
		invoker.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				hideIt();
			}
		});
	}

	/**
	 * Shows the popup with the specified text
	 * 
	 * @param text
	 *            the String to show
	 */
	public void showIt(String text) {
		hideIt();
		JMenuItem item = new JMenuItem(text);
		item.setBorder(BorderFactory.createEmptyBorder());
		if (invoker.isShowing()) {
			add(item);
			setVisible(true);
		}
	}

	/**
	 * Hides the popup
	 */
	public void hideIt() {
		removeAll();
		setVisible(false);
	}

}
